package com.laikan.reader.bookshelf.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.*;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.DeviceUtil;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.bookreader.activity.ReaderDetailActivity;
import com.laikan.reader.core.adapter.ReadHistoryAdapter;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.database.Book;
import com.laikan.reader.database.DBBook;
import com.laikan.reader.database.DBHistory;
import com.laikan.reader.database.History;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

/**
 * 阅读历史界面
 * Created by gwt on 2016/10/25.
 */
public class ReadHistoryActivity extends BasicActivity {

    private int record_num = 0;
    private ListView listview;
    private RelativeLayout rl_title;    //显示全选和返回的title
    private ReadHistoryAdapter mAdapter;
    private List<History> histories = new ArrayList<>();    //历史记录
    private List<History> deleteDate = new ArrayList<>();   //待删除记录
    private TextView tv_select_all, tv_action_back;         //完成
    private ItemClickListener itemClickListener = new ItemClickListener();  //条目单击监听
    private boolean select_flag = false;    //表示所有item处于选中状态时为true, 否则为false
    private RelativeLayout rl_tab;  //显示浏览历史title
    private TextView tv_edit;
    private TextView tv_buttom_del;
    private RelativeLayout rl_del;
    private Drawable drawable_back_tv;
    private ImageView back_tv;
    private RelativeLayout back_layout;
    private ImageView iv_book_del;
    private Drawable iv_book_del_drawable;

    @Override
    protected void assignViews() {
        setContentView(R.layout.activity_read_history);
        rl_title = (RelativeLayout)findViewById(R.id.rl_title); //编辑历史记录后的标题（全选 -- 完成）
        rl_del = (RelativeLayout)findViewById(R.id.rl_del);     // 底部删除的布局
        listview = (ListView)findViewById(R.id.listview);
        tv_select_all = (TextView)findViewById(R.id.tv_select_all);   //全选按钮
        tv_action_back = (TextView)findViewById(R.id.tv_action_back); // 完成按钮
        rl_tab = (RelativeLayout)findViewById(R.id.rl_tab);   //历史记录标题的返回按钮(返回-- 标题 -- 编辑)
        tv_edit = (TextView)findViewById(R.id.tv_edit);   //编辑按钮
        tv_buttom_del = (TextView)findViewById(R.id.tv_buttom_del); //底部删除布局中的文本
        back_tv = (ImageView)findViewById(R.id.back_tv);
        iv_book_del = (ImageView)findViewById(R.id.iv_book_del);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
    }

    @Override
    protected void initData() {
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext,R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        back_tv.setImageDrawable(drawable_back_tv);
        iv_book_del_drawable = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(this, R.drawable.lk_book_del), Color.parseColor("#ffffff")));
        iv_book_del.setImageDrawable(iv_book_del_drawable);
        openEventBus();
        histories = DBHistory.getInstance().queryAllHistory();
        mAdapter = new ReadHistoryAdapter(mContext, histories);
        listview.setAdapter(mAdapter);
    }

    @Override
    protected void setListener() {
        listview.setOnItemClickListener(itemClickListener);
        tv_select_all.setOnClickListener(this);
        tv_action_back.setOnClickListener(this);
        tv_edit.setOnClickListener(this);
        rl_del.setOnClickListener(this);
        back_layout.setOnClickListener(this);
    }

    private boolean delIsShow = false;

    @Override
    protected void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.back_layout:
                finish();
                break;
            case R.id.tv_select_all:
                checkSelectAll();
                break;
            case R.id.tv_action_back: //完成
                actionBack();
                break;
            case R.id.rl_del: // 删除
                if (deleteDate.size() > 0) {
                    MobclickAgent.onEvent(mContext, "sj-sy-cd-ls-sc");//书架-首页-菜单-浏览历史-删除
                    DBHistory.getInstance().deleteBookList(deleteDate);
                    histories.removeAll(deleteDate);
                    record_num = 0;
                    deleteDate.clear();
                    recordBookDeleete(record_num);
                    mAdapter.updataSelector(true);
                    select_flag = false;
                    tv_select_all.setText(R.string.history_select_all);
                    for(int i = 0;i<deleteDate.size();i++){
                        String bookid = deleteDate.get(i).getBookId();
                        SPUtil.putInt(bookid + "chaptep_rec", 0);
                        SPUtil.putInt(bookid + "recCurPage", 0);
                    }
                }else {
                    ToastMgr.showShortToast(R.string.no_select_history);
                }
                break;
            case R.id.tv_edit: //编辑
                if (!delIsShow) {
                    rl_del.setVisibility(View.VISIBLE);
                }else {
                    rl_del.setVisibility(View.GONE);
                }
                delIsShow = !delIsShow;
                bookDeleteManager();
                break;
            default:
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if(rl_title.getVisibility() == View.VISIBLE){
            actionBack();
            updateData();
            return;
        }
    }

    /**
     *  编辑的时候屏蔽返回键
     */
    @Override
    public void onBackPressed() {
        if(rl_title.getVisibility() == View.VISIBLE){
            actionBack();
            return;
        }
        super.onBackPressed();
    }

    private void updateData() {
        histories.clear();
        histories = DBHistory.getInstance().queryAllHistory();
        mAdapter.updataAll(histories);
    }

    /**
     * RL_Tab 显示时 rl_title 不能显示,
     */
    private void reverseTitle() {
        if (rl_title.getVisibility() == View.GONE) {
            rl_title.setVisibility(View.VISIBLE);
            rl_tab.setVisibility(View.GONE);
        }else {
            rl_title.setVisibility(View.GONE);
            rl_tab.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 检查全选状态,完成全选(全不选)动作
     */
    private void checkSelectAll() {
        deleteDate.clear();
        if (!select_flag) {
            tv_select_all.setText(R.string.history_select_cancle);
            record_num = histories.size();
            for (History h : histories) {
                h.setSelected(true);
                deleteDate.add(h);
            }
            select_flag = true;
        }else {
            tv_select_all.setText(R.string.history_select_all);
            record_num = 0;
            for (History h : histories) {
                h.setSelected(false);
            }
            select_flag = false;
        }
        mAdapter.updataSelector(true);
        recordBookDeleete(record_num);
    }

    /**
     * 返回按钮和物理返回执行动作
     */
    public void actionBack() {
        if (rl_title.getVisibility() == View.VISIBLE) {
            rl_del.setVisibility(View.GONE);
            delIsShow = false;
            reverseTitle();
            histories = DBHistory.getInstance().queryAllHistory();
            for (History h : histories) {
                h.setSelected(false);
            }
            deleteDate.clear();
            mAdapter.updataAll(histories);
            record_num = 0;
            recordBookDeleete(record_num);
            select_flag = false;
            tv_select_all.setText(R.string.history_select_all);
        }
    }

    private void bookDeleteManager() {
        reverseTitle();
        mAdapter.updataSelector(true);
        listview.setOnItemLongClickListener(null);
        recordBookDeleete(record_num);
    }

    private void recordBookDeleete(int delCount) {
        tv_buttom_del.setText(DeviceUtil.getHtmlFormatedString(ReadHistoryActivity.this, R.string.book_has_selected, delCount));
    }

    /**
     * 点击历史记录 进入阅读页
     *
     * @param b
     */
    private void readChaper(Book b) {
        MobclickAgent.onEvent(mContext, "sj-sy-cd-ls-xc");//书架-首页-菜单-浏览历史-详情
        Intent intent = new Intent();
        intent.setClass(mContext, ReaderDetailActivity.class);
        intent.putExtra("bookDes", b);
        startActivity(intent);
    }

    private class ItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            MobclickAgent.onEvent(mContext, "bookshelf_history");
            if (!(rl_title.getVisibility() == View.VISIBLE)) {
                History history = (History)mAdapter.getItem(position);
                Book book = DBBook.getInstance().queryBookById(history.getBookId());
                if (book == null) {
                    book = history.convertBookBean();
                }
                readChaper(book);
            }else {
                History h = histories.get(position);
                if (h.getSelected()) {
                    h.setSelected(false);
                    deleteDate.remove(h);
                    record_num--;
                    if (record_num == 0) {
                        select_flag = false;
                        tv_select_all.setText(R.string.history_select_all);
                    }
                }else {
                    h.setSelected(true);
                    deleteDate.add(h);
                    record_num++;
                    if (record_num == histories.size()) {
                        select_flag = true;
                        tv_select_all.setText(R.string.history_select_cancle);
                    }
                }
                mAdapter.updataSelector(true);
                recordBookDeleete(record_num);
            }
        }
    }

}
